﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace ThreeByte.ActiveDeck.Data.UserResponse {

    /// <summary>
    /// Gets Total Correct percentages per group
    /// </summary>
    public class GroupedUserResponseResultsData {
        protected static readonly XNamespace ns = Service.ServiceConfiguration.NAMESPACE;

        public string Presentation {
            get;
            private set;
        }

        //public int Section {
        //    get;
        //    protected set;
        //}

        public Dictionary<int, float> GroupedResults {
            get;
            set;
        }

        public GroupedUserResponseResultsData(string presentation) {
            Presentation = presentation;
            GroupedResults = new Dictionary<int, float>();
        }

        public XElement ToXml(){
            XElement node = new XElement(ns + "GroupedData", new XAttribute("Presentation", Presentation));

            foreach(int k in GroupedResults.Keys.OrderBy(p => p)) {
                XElement groupNode = new XElement(ns + "Group", new XAttribute("ID", k), new XAttribute("Correct", GroupedResults[k].ToString()));
                
                node.Add(groupNode);
            }

            return node;
        }

        public static GroupedUserResponseResultsData ParseXml(XElement node) {

            GroupedUserResponseResultsData aggGroupedResponseData = new GroupedUserResponseResultsData(node.Attribute("Presentation").Value);

            foreach(XElement g in node.Elements(ns + "Group")) {
                aggGroupedResponseData.GroupedResults.Add(int.Parse(g.Attribute("ID").Value), float.Parse(g.Attribute("Correct").Value));
            }

            return aggGroupedResponseData;
        }

        public bool UpdateUserResponseResultsData(Dictionary<int, float> newData) {
            
            bool modified = false;
            foreach(int k in newData.Keys) {

                //check if the old data contains the group
                if(GroupedResults.ContainsKey(k)) {
                    //check if the old percentage is different from the new percentage
                    if(newData[k] != GroupedResults[k]) {
                        //set new percentage
                        GroupedResults[k] = newData[k];
                        modified = true;
                    }
                } else {
                    //Add the new group and percentage
                    GroupedResults.Add(k, newData[k]);
                    modified = true;
                }
            }

            return modified;
        }




    }
}
